package com.hangwei.paperless;

import android.Manifest;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.View;

import com.hangwei.paperless.fragment.sub.SubEditSetListFragment;
import com.hangwei.paperless.model.bean.CardToSeal;
import com.hangwei.paperless.model.bean.SubSetInfo;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.NFCCallBack;
import com.hangwei.paperless.widget.CardSealPop;
import com.hangwei.paperless.widget.ViewPagerFixed;
import com.twelve.all.base.NFCApp;
import com.twelve.all.net.CallBack;
import com.twelve.all.nfc.BasicActivity;
import com.twelve.all.nfc.Constants;
import com.twelve.all.nfc.MCReader;
import com.twelve.all.nfc.PreferencesUtil;
import com.twelve.all.nfc.Utils;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 张龙臣 on 2020/12/8.
 */

public class EditSubSetListActivity extends BasicActivity {

    private MyViewPagerAdapter mViewPagerAdapter;
    private String mUserId = SPUtil.getString(SPKey.Account.USER_ID);
    private String mBillId;
    private ArrayList<String> mPicList;
    private String mSubId;
    private String mPositionId;
    private ViewPagerFixed mViewPager;
    private boolean mCanCard;
    private String stepId;
    private NFCCallBack mNFCCallBack;
    private CardSealPop mCardSealPop;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_set_list);
        findViewById(R.id.view0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mBillId = getIntent().getStringExtra("billId");
        mPicList = getIntent().getStringArrayListExtra("picList");
        mSubId = getIntent().getStringExtra("id");
        mPositionId = getIntent().getStringExtra("itemId");
        mViewPager = findViewById(R.id.viewPager);
        mViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mViewPagerAdapter);
        initData();
    }

    private void initData() {
        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.show();
        StaticPresenter.getBushInstallationSheet(mUserId, mBillId, mSubId, new CallBack<List<SubSetInfo>>() {
            @Override
            public void onCompleted(List<SubSetInfo> subSetInfos) {
                loadingDialog.dismiss();
                mViewPagerAdapter.setData(subSetInfos);
                if (subSetInfos != null)
                    for (int i = 0; i < subSetInfos.size(); i++) {
                        SubSetInfo info = subSetInfos.get(i);
                        if (info.id.equals(mPositionId)) {
                            mViewPager.setCurrentItem(i, false);
                            break;
                        }
                    }
            }

            @Override
            public void onError() {
                loadingDialog.dismiss();
            }
        });
    }

    private class MyViewPagerAdapter extends FragmentStatePagerAdapter {
        private List<SubSetInfo> mData;

        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            SubEditSetListFragment fragment = new SubEditSetListFragment();
            Bundle bundle = new Bundle();
            SubSetInfo partCheckInfo = mData.get(i);
            bundle.putSerializable("item", partCheckInfo);
            bundle.putStringArrayList("picList", mPicList);
            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }

        public void setData(List<SubSetInfo> data) {
            mData = data;
            notifyDataSetChanged();
        }
    }
    @Override
    public void onNewIntent(Intent intent) {
        if (mCanCard && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            tag = MCReader.patchTag(tag);
//            setTag(tag);
//            Utils.logUid(Utils.byte2Hex(tag.getId()));

            boolean isCopyUID = PreferencesUtil.getPreferences().getBoolean(
                    Constants.AutoCopyUID, false);
            if (isCopyUID) {
                int format = PreferencesUtil.getPreferences().getInt(
                        Constants.UIDFormat, 0);
                String fmtUID = Utils.byte2FmtString(tag.getId(), format);
            } else {
                // Show Toast message with UID.
                String msg = Utils.byte2Hex(tag.getId());
                LogUtil.i(msg);
                LoadingDialog loadingDialog = new LoadingDialog(this);
                loadingDialog.show();
                String userId = SPUtil.getString(SPKey.Account.USER_ID);
                StaticPresenter.getUserByCardId(userId, mBillId, stepId, msg, new CallBack<CardToSeal>() {
                    @Override
                    public void onCompleted(CardToSeal cardToSeal) {
                        loadingDialog.dismiss();
                        if (mNFCCallBack != null)
                            mNFCCallBack.onCallBack(cardToSeal.stamp, cardToSeal.userId);
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                    }

                    @Override
                    public void onError() {
                        loadingDialog.dismiss();
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                        ToastUtil.showCenterToast("获取印章失败！");
                    }
                });


            }
//            return Utils.checkMifareClassicSupport(tag, context);
        }
    }
    public void sealByCard(String id, NFCCallBack NFCCallBack) {
        if (NFCApp.hasWritePermissionToExternalStorage(EditSubSetListActivity.this)) {
            NFCApp.setUseAsEditorOnly(NFCApp.useAsEditorOnly());
            runStartUpNode(StartUpNode.FirstUseDialog);
            stepId = id;
            mNFCCallBack = NFCCallBack;
            if (mCardSealPop == null)
                mCardSealPop = new CardSealPop(this,false) {
                    @Override
                    protected void onDismiss1() {
                        mCanCard = false;
                    }
                };
            if (!mCardSealPop.isShowing())
                mCardSealPop.show();
//                mCardSealPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            mCanCard = true;
        } else {
            ActivityCompat.requestPermissions(EditSubSetListActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        }
    }

    @Override
    public void finish() {
        if (mCardSealPop!=null&&mCardSealPop.isShowing()){
            mCardSealPop.dismiss();
            return;
        }
        super.finish();
    }
}
